﻿using CRM.Models;
using CRM.Services;
using System.Linq;
using CRM.Extensions;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using System;
using Microsoft.AspNetCore.Identity;
using CRM.ViewModels.User;
using System.Collections.Generic;

namespace CRM.Controllers.SystemManage
{
    [Route("api/[controller]")]
    [ApiController]
    public class JuniorController : BaseController
    {
        private readonly MyDbContext _dbContext;
        private readonly UserManager<User> userManager;
        private readonly UserService _UserService;
        private readonly CompanyService _CompanyService;

        public JuniorController(MyDbContext dbContext, UserManager<User> userManager, UserService userService, CompanyService companyService)
        {
            _dbContext = dbContext;
            this.userManager = userManager;
            _UserService = userService;
            _CompanyService = companyService;
        }

        /// <summary>
        /// 下级信息列表数据
        /// </summary>
        /// <param name="RequestData"></param>
        /// <returns></returns>
        [HttpGet("[Action]")]
        public async Task<ResultStruct> GetJuniorList([FromQuery] GetJuniorList RequestData)
        {
            CompanyUserData UserData = null;
            var UserList = new Dictionary<int, CompanyUserData>();
            var ResultsUserTotal = new Dictionary<int, JuniorTotalNumData>();
            var ResultsRuleTemplates = new Dictionary<int, RuleTemplateService.ChooseData>();
            //返回数据类型
            var ReturnData = new ReturnJuniorList()
            {
                CompanyData = new
                {
                    Total = 0,
                    CurrentPage = 1,
                    PageSize = 1,
                    Items = new int[] { }
                },
                UserList = UserList,
                UserTotal = ResultsUserTotal,
                RuleTemplates = ResultsRuleTemplates
            };
            Company CurrentCompany = null;

            int RequestCompanyId = RequestData.CompanyId;
            if (RequestCompanyId == 0)
            {
                var u = userManager.GetUserAsync(User).Result;
                CurrentCompany = _CompanyService.GetInfo(u.CompanyId);
            }
            else
            {
                CurrentCompany = _CompanyService.GetInfo(RequestCompanyId);
            }

            int CompanyId = 0;

            //用户名搜索，先搜索用户信息
            if (!string.IsNullOrEmpty(RequestData.Name))
            {
                UserData = _dbContext.Users.Where(i => i.Type == Models.User.Types.CompanyAdmin)
                    .Where(i => i.HashCode == Helper.GetDeterministicHashCode(RequestData.Name)).Select(n =>
                        new CompanyUserData()
                        {
                            Id = n.Id,
                            UserName = n.UserName,
                            TrueName = n.TrueName,
                            CompanyId = n.CompanyId
                        }).FirstOrDefault();

                //无用户 直接让返回
                if (UserData == null)
                {
                    return Success(ReturnData);
                }
                //检测查询用户公司信息是否是指定公司下级
                Company CompanyInfo = _CompanyService.GetInfo(UserData.CompanyId);
                if (CompanyInfo.ParentCompanyId != CurrentCompany.Id)
                {
                    return Success(ReturnData);
                }

                ReturnData.UserList[UserData.CompanyId] = UserData;
                CompanyId = UserData.CompanyId;
            }

            RuleTemplateService RuleTemplateService = new(_dbContext);
            var RuleTemplates = RuleTemplateService.GetAllRuleTemplate(CurrentCompany.Id, CurrentCompany.OemId);
            ReturnData.RuleTemplates = RuleTemplates.ToDictionary(k => k.Id);


            IQueryable<Company> sqlQuery = _dbContext.Company.Where(i => i.ParentCompanyId == CurrentCompany.Id);
            IQueryable<User> userTotalSqlQuery = _dbContext.Users;

            if (CompanyId != 0)
            {
                sqlQuery = sqlQuery.Where(i => i.Id == CompanyId);
                userTotalSqlQuery = userTotalSqlQuery.Where(i => i.CompanyId == CompanyId);
            }
            if (!string.IsNullOrEmpty(RequestData.ValidityStart))
            {
                long ValidityStart = Helper.GetTimeStamp(Convert.ToDateTime(RequestData.ValidityStart));
                long ValidityEnd = Helper.GetTimeStamp(Convert.ToDateTime(RequestData.ValidityEnd));

                sqlQuery = sqlQuery.Where(i => i.ShowValidity >= ValidityStart);
                sqlQuery = sqlQuery.Where(i => i.ShowValidity <= ValidityEnd);
            }
            //公司信息分页数据
            var CompanyData = await sqlQuery.Select(n =>
                new CompanyListData()
                {
                    Id = n.Id,
                    Name = n.Name,
                    RuleId = n.RuleId,
                    State = n.State,
                    Validity = Helper.TimeStampToDate(n.ShowValidity),
                    OemId = n.ShowOemId,
                    CreatedAt = n.CreatedAt
                }).OrderBy(i => i.State).OrderByDescending(i => i.Id).ToPaginateAsync(Request);
            //取出对应公司下管理员账号信息
            if (UserData == null)
            {
                var CompanyIds = CompanyData.Items.Select(m => m.Id);
                userTotalSqlQuery = userTotalSqlQuery.Where(m => CompanyIds.Contains(m.CompanyId));

                var UserDataList = _dbContext.Users.Where(i => i.Type == Models.User.Types.CompanyAdmin).
                    Where(m => CompanyIds.Contains(m.CompanyId)).Select(n =>
                    new CompanyUserData()
                    {
                        Id = n.Id,
                        UserName = n.UserName,
                        TrueName = n.TrueName,
                        CompanyId = n.CompanyId
                    }).ToList();

                ReturnData.UserList = UserDataList.ToDictionary(k => k.CompanyId);
            }

            ReturnData.CompanyData = CompanyData;

            //公司下用户汇总 SELECT count(CompanyId),CompanyId FROM user GROUP BY CompanyId
            var UserTotal = userTotalSqlQuery.
                GroupBy(p => new { p.CompanyId })
                .Select(n => new JuniorTotalNumData()
                {
                    CompanyId = n.Key.CompanyId,
                    Total = n.Count()
                });

            ReturnData.UserTotal = UserTotal.ToDictionary(k => k.CompanyId);

            return Success(ReturnData);
        }


        public record ChooseEmployeeData(string UserName, string TrueName, DateTime CreatedAt);
        [HttpGet("[Action]")]
        public async Task<ResultStruct> GetJuniorEmployeeList([FromQuery] GetDataId RequestData)
        {
            var data = await _dbContext.Users.
               Where(i => i.CompanyId == RequestData.Id).
               Where(i => i.Type == Models.User.Types.Employee).
               Select(n => new ChooseEmployeeData
                (
                    n.UserName,
                    n.TrueName,
                    n.CreatedAt
                )).
               ToPaginateAsync(Request);
            return Success(data);
        }


    }
}